const {mysql} = require('../qcloud')

module.exports = async (ctx)=>{
  const {bookid, openid} = ctx.request.query
  const mysqlSelect = mysql('comments')
                            .select('comments.*','cSessionInfo.user_info')
                            .join('cSessionInfo','comments.openid','cSessionInfo.open_id')
                            // .where('bookid',bookid)
                            // .orderBy('id','desc')
  let comments
  if(bookid){
    //图书详情页的评论获取
    comments = await mysqlSelect.where('bookid',bookid).orderBy('id','desc')
  }else if(openid){
    //根据openid获取个人所有评论
    comments = await mysqlSelect.where('openid',openid).orderBy('time','desc')
  }
  ctx.state.data = {
    list:comments.map(v=>{
      const info = JSON.parse(v.user_info)
      return Object.assign({},v,{
        user_info:{
          name:info.nickName,
          img:info.avatarUrl
        }
      })
    })
  }
}